﻿using System.Data.Common;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySql.Data.MySqlClient;

namespace Micro.Extensions.Data
{
    public  class DbConnectionFactory:IDbConnectionFactory
    {
        private static ushort _dbIndex;
        private readonly ILogger _logger;
        private  string _connStrMain;
        private  string[] _connStrReplicas;
        private  int _executeSqlElapsedTimeWarning;

        public DbConnectionFactory(IOptionsMonitor<DataConfig> dataOptionsMonitor, ILogger<DbConnectionFactory> logger)
        {
            _logger = logger;
            _connStrMain = dataOptionsMonitor.CurrentValue.MasterConn;
            _connStrReplicas = dataOptionsMonitor.CurrentValue.ReplicasConn;
            _executeSqlElapsedTimeWarning = dataOptionsMonitor.CurrentValue.ExecuteSqlElapsedTimeWarning;
            dataOptionsMonitor.OnChange(c =>
            {
                _connStrMain = c.MasterConn;
                _connStrReplicas = c.ReplicasConn;
                _executeSqlElapsedTimeWarning = c.ExecuteSqlElapsedTimeWarning;

            });
        }
        public DbConnection GetDbConnection(bool master = true)
        {
            if (master)
            {
                return new ConnectionProxy(new MySqlConnection(_connStrMain), _executeSqlElapsedTimeWarning, _logger);
            }

            //没有从库
            if (_connStrReplicas == null || _connStrReplicas.Length == 0)
            {
                return new ConnectionProxy(new MySqlConnection(_connStrMain), _executeSqlElapsedTimeWarning, _logger);
            }

            //从库轮询
            _dbIndex++;
            var index = _dbIndex % _connStrReplicas.Length;
            return new ConnectionProxy(new MySqlConnection(_connStrReplicas[index]), _executeSqlElapsedTimeWarning, _logger);
        }
    }
}
